package com.cxm.qyyz.core.http.interceptor;

import android.text.TextUtils;

import com.blankj.utilcode.util.GsonUtils;
import com.cxm.qyyz.app.Constants;
import com.cxm.qyyz.core.http.ApiException;
import com.cxm.qyyz.core.http.BaseResponse;
import com.cxm.qyyz.utils.flow.LogUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.GzipSource;

public class ResponseInterceptor implements Interceptor {

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        String url = request.url().toString();
        printUrl(request);
        Response response = chain.proceed(request);
        ResponseBody responseBody = response.body();
        if (responseBody != null) {
            long contentLength = responseBody.contentLength();
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.getBuffer();
            if ("gzip".equals(response.headers().get("Content-Encoding"))) {
                GzipSource gzippedResponseBody = new GzipSource(buffer.clone());
                buffer = new Buffer();
                buffer.writeAll(gzippedResponseBody);
            }
            MediaType contentType = responseBody.contentType();
            Charset charset;
            if (contentType == null || contentType.charset(StandardCharsets.UTF_8) == null) {
                charset = StandardCharsets.UTF_8;
            } else {
                charset = contentType.charset(StandardCharsets.UTF_8);
            }
            if (charset != null && contentLength != 0L) {
                return intercept(response, url, buffer.clone().readString(charset));
            }
        }
        return response;
    }

    @SuppressWarnings("unchecked")
    private Response intercept(Response response, String url, String body) {
        String targetUrl = url;
        if (!"post".equalsIgnoreCase(response.request().method())) {
            if (url.contains("?")) {
                targetUrl = url.substring(0, url.indexOf("?"));
            }
        }
        try {
            BaseResponse baseResponse = GsonUtils.fromJson(body, BaseResponse.class);
            int errCode = baseResponse.getCode();
            if (errCode != 0) {
                String errorMsg = baseResponse.getMessage();
                throw new ApiException(errCode, errorMsg);
            } else {
                if (baseResponse.getData() == null) {
                    if (Constants.targetUrls.contains(targetUrl)) {
                        baseResponse.setData("");
                        return response.newBuilder()
                                .body(ResponseBody.create(GsonUtils.toJson(baseResponse), MediaType.get("text/plain")))
                                .build();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    private void printUrl(Request request) {
        if (request == null) return;
        HttpUrl httpUrl = request.url();
        String scheme = httpUrl.scheme();
        String host = httpUrl.host();
        String path = httpUrl.encodedPath();
        String query = httpUrl.encodedQuery();

        StringBuilder sb = new StringBuilder();
        sb.append(scheme).append("://").append(host).append(path);
        if (!TextUtils.isEmpty(query)) {
            sb.append("?").append(query);
        }
        LogUtils.d("<----####！！ 完整的的访问链接(含参数) ！！####---->    " + sb);
    }
}